<?php

namespace apiend\modules\user\models;

use Yii;
use common\helpers\Url;

/**
 * 用户会话列表
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ConversationUserSearch extends \common\models\user\User {

    public $ids;
    private $_uids = [];

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['ids'], 'string'],
            [['ids'], 'validateIds'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function validateIds($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $ids = array_unique(array_filter(explode(',', $this->$attribute)));
        if (!empty($ids)) {
            $this->_uids = $ids;
        }
    }

    /**
     * @return \yii\data\ActiveDataProvider
     */
    public function search() {
        $this->validate();
        $uids = $this->_uids;
        if (empty($uids)) {
            return [];
        }
        $cacheDuration = YII_DEBUG ? 0 : 60;
        return $this->find()->andWhere([
            'id' => $uids,
        ])->cache($cacheDuration)->all();
    }

    /**
     * @internal
     */
    public function fields() {
        return [
            'id',
            'nickname' => function() {
                return $this->nickname ?: $this->username;
            },
            'avatar' => function() {
                return Url::attach($this->avatar);
            },
        ];
    }

}
